package com.jishaokang.service.impl;

import com.jishaokang.base.Result;
import com.jishaokang.cache.ResultCache;
import com.jishaokang.dao.MessageDAO;
import com.jishaokang.model.dto.Message;
import com.jishaokang.model.vo.MessageVO;
import com.jishaokang.service.MessageService;
import com.jishaokang.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Created by NANA_Final on 2019/6/21.
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDAO messageDAO;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public Result selectTotalUnreadMessage(Message message) {
        int userId = tokenUtil.getUserIdByToken(message.getToken());
        message.setReceiverId(userId);
        int total = messageDAO.selectTotalUnread(message);
        return ResultCache.getListDataOk(total,"messages",null);
    }

    @Override
    public Result selectMessageByReceiverId(Message message) {
        int userId = tokenUtil.getUserIdByToken(message.getToken());
        message.setReceiverId(userId);
        int total = messageDAO.selectTotalByReceiverId(message);
        message.setPage((message.getPage()-1)*message.getNumber());
        List<MessageVO> messages = messageDAO.selectByReceiverId(message);
        return ResultCache.getListDataOk(total,"messages",messages);
    }

    @Override
    public Result selectMessageByMessageId(Message message) {
        MessageVO messageVO= messageDAO.selectByMessageId(message);
        return ResultCache.getDataOk(messageVO);
    }

    @Override
    public Result updateMessageStateByMessageId(Message message) {
        messageDAO.updateStateByMessageId(message);
        return ResultCache.OK;
    }

    @Override
    public Result deleteMessageByMessageId(Message message) {
        messageDAO.deleteByMessageId(message);
        return ResultCache.OK;
    }

    @Override
    public Result updateMessagesStatesByReceiverId(Message message) {
        int userId = tokenUtil.getUserIdByToken(message.getToken());
        message.setReceiverId(userId);
        messageDAO.updateStatesByReceiverId(message);
        return ResultCache.OK;
    }

    @Override
    public Result deleteMessagesByReceiverIdAndState(Message message) {
        int userId = tokenUtil.getUserIdByToken(message.getToken());
        message.setReceiverId(userId);
        messageDAO.deleteByReceiverIdAndState(message);
        return ResultCache.OK;
    }


}